
<template>
  <div class="accountList">
    <div class="searchBox">
      <el-form :model="searchForm" ref="searchFormRef">
        <el-row>
          <el-form-item prop="title">
            <div class="item">
              <span v-html="'标题'" class="nameSpan"></span>
              <el-input
                size="mini"
                v-model="searchForm.title"
                placeholder="请输入标题"
              ></el-input>
            </div>
          </el-form-item>

          <el-form-item prop="tag">
            <div class="item">
              <span v-html="'标签'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.tag"
                placeholder="请选择标签"
                size="mini"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.v"
                  :label="item.v"
                  :value="item.k"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              @click="searchClick"
              icon="el-icon-search"
              type="primary"
              size="mini"
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetClick"
              >重置</el-button
            >
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <div class="topBtn">
      <el-button
        v-has="'law_standard:standard_lib:add'"
        size="mini"
        @click="addAccountClick"
        type="success"
        plain
        icon="el-icon-plus"
        >新增文库</el-button
      >
    </div>

    <div class="tableBox" ref="tableBoxRef">
      <el-table
       :height="605"
        v-loading="tableLoading"
        :header-cell-style="{
          background: '#F8F8F8',
          color: '#333',
          fontSize: '16px',
          fontWeight: '700',
        }"
        border
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          prop="title"
          align="center"
          label="标题"
           
        >
        </el-table-column>
        <el-table-column
          prop="tag"
          align="center"
          label="标签"
           
        >
          <template slot-scope="scope">
            <div>{{ tagMap[scope.row.tag]||'-' }}</div>
         
          </template>
        </el-table-column>
        <el-table-column
          prop="publishDate"
          align="center"
          label="发布日期"
           
        >
        </el-table-column>
        <el-table-column
          prop="implementDate"
          align="center"
          label="实施日期"
           
        >
        </el-table-column>
        <el-table-column
          prop="publishDepartment"
          align="center"
          label="发布部门"
           
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              v-has="'law_standard:standard_lib:edit'"
              @click="editClick(scope.row, scope.$index)"
              >编辑</el-button
            >
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="text"
              @click="delClick(scope.row)"
              v-has="'law_standard:standard_lib:delete'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

     <el-card class="footer" v-if="total > 0">
         <div>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[15, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
       </el-card>
    </div>

    <!-- 新增/修改权限 -->
    <el-dialog :close-on-click-modal="false" 
      :title="title"
      :visible.sync="addEditDialogVisible"
      width="600px"
      @open="addEditDialogOpen"
      class="addEditAccountDialog"
    >
      <div class="content">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditFormRef"
        >
          <el-form-item prop="title" label="标题：">
            <div class="item">
              <el-input
                size="mini"
                v-model="addEditForm.title"
                placeholder="请输入标题"
                maxlength="200"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="tag" label="标签：">
                <div class="item">
                  <el-select filterable 
                    clearable
                    size="mini"
                    v-model="addEditForm.tag"
                    placeholder="请选择标签"
                  >
                    <el-option
                      v-for="item in typeOptions"
                      :key="item.v"
                      :label="item.v"
                      :value="item.k"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="11" style="margin-left: 30px">
              <el-form-item prop="publishDepartment" label="发布部门：">
                <div class="item">
                  <el-input
                    size="mini"
                    v-model="addEditForm.publishDepartment"
                    placeholder="请输入发布部门"
                  >
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item prop="publishDate" label="发布日期：">
                <div class="item">
                  <el-date-picker
                    style="width: 256px"
                    value-format="yyyy-MM-dd"
                    size="mini"
                    v-model="addEditForm.publishDate"
                    type="date"
                    placeholder="发布日期"
                  >
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="11" style="margin-left: 30px">
              <el-form-item prop="implementDate" label="实施日期：">
                <div class="item">
                  <el-date-picker
                    style="width: 256px"
                    value-format="yyyy-MM-dd"
                    size="mini"
                    v-model="addEditForm.implementDate"
                    type="date"
                    placeholder="实施日期"
                  >
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="attachmentUrl" label="附件上传：">
            <div class="item">
              <el-upload
                :before-upload="beforeUpload"
                accept=".pdf"
                :headers="postHead"
                class="upload-demo"
                :action="$uploadUrl + '/3'"
                :on-success="handleSuccess"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
                :show-file-list="false"
                  :on-change='handleChange'
              >
                <div style="color: #409eff" v-if="addEditForm.attachmentUrl">
                  {{ addEditForm.attachmentName }}
                  <div>点击替换上传</div>
                </div>
                <el-button v-else size="small" type="primary"
                  >点击上传</el-button
                >
              </el-upload>
                <el-progress
      v-if="showJinDuTaoExcel"
      style="width: 200px; margin-top:10px;margin-left:30px   "
      :percentage="progressPercentExcel"
    />
              <div>仅能上传pdf文件，且不超过100M</div>
            </div>
          </el-form-item>
          <el-form-item class="btns">
            <el-button size="mini" @click="addEditDialogVisible = false"
              >取 消</el-button
            >
            <el-button
              v-clickForbidden
              size="mini"
              type="primary"
              @click="addEditDialogSaveClick"
              >确 定</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
    
         progressPercentExcel: 0, // 进度条默认为0
       showJinDuTaoExcel: false, //控制进度条显示隐藏
      typeOptions: [],
      typeFormatter: {},
      postHead: { token: localStorage.token },
      searchForm: {
        title: "",
        tag: "",
      },
      stautsOptions: [
        { label: "正常", value: 1 },
        { label: "禁用", value: 2 },
      ],
      tableLoading: false,
      tableHeight: 50,
      tableData: [],
      pageNum: 1,
      pageSize: 15,
      total: 0,
      addEditDialogVisible: false,
      addEditForm: {
        attachmentName: "",
        attachmentUrl: "",
        implementDate: "",
        publishDate: "",
        publishDepartment: "",
        tag: 1,
        title: "",
      },
      addEditRules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        //  tag: [
        //   { required: true, message: "标签不能为空", trigger: "blur" },
        // ],
        publishDate: [
          { required: true, message: "发布日期不能为空", trigger: "blur" },
        ],
      },
      roleOptions: [],
      title: "新增文库",
      editId: "",
    };
  },
  computed: {
    ...mapGetters(["dictList"]),
     tagMap() {
      let map = {}
      this.typeOptions.forEach(x => {
        map[x.k] = x.v
      })
      return map
    },
  },

  created() {
    this.getStandardList();
  },
  methods: {
     handleChange( file, fileList){
       
      if(file.status==='ready'){
       
          this.progressPercentExcel =0
          this.showJinDuTaoExcel=true
          const interval=setInterval(()=>{
            if(this.progressPercentExcel>=99){
              clearInterval(interval)
              return
            }
            this.progressPercentExcel+=1
          },100)
      }
      if(file.status==='success'){
        this.progressPercentExcel=100
         setTimeout(()=>{
          this.showJinDuTaoExcel=false
         
        },1000)
      }
       if(file.status==='fail'){
         setTimeout(()=>{
          this.progressPercentExcel = 0;
          this.showJinDuTaoExcel=false
          this.progressPercentExcel=0
        },1000)
      }
      
    },
       
    resetClick() {
      this.$refs.searchFormRef.resetFields();
      this.pageNum = 1;
      this.getStandardList();
    },
    searchClick() {
      this.pageNum = 1;
      this.getStandardList();
    },
    handleSuccess(file, fileList) {
      this.$nextTick(() => {
        this.addEditForm.attachmentUrl = file.result.filePath;
        this.addEditForm.attachmentName = fileList.name;
        console.log(this.addEditForm);
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能上传一个附件");
    },

    handleRemove(obj) {
      this.$nextTick(() => {
        this.addEditForm.attachmentUrl = "";
        this.addEditForm.attachmentName = "";
      });
    },
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "pdf";
      const isLt100M = file.size / 1024 / 1024 < 100;
      if (!extension) {
         this.$message.error("上传文件只能是pdf格式!");
            file=false
       return file
      }
      if (!isLt100M) {
         this.$message.error("上传文件大小不能超过 100MB!");
           file=false
       return file
      }
     this.$message.warning('上传中，请稍等')
        
       
    },

    /**
     * 获取标准库列表
     * @param {*}
     */
    async getStandardList() {
      this.tableLoading = true;
      const res = await this.$api.standardList({
        size: this.pageSize,
        page: this.pageNum,
        condition: {
          ...this.searchForm,
        },
      });
      this.total = res.data.result.total;
      this.tableData = res.data.result.records;
      this.typeOptions = this.dictList.laws_label;
      this.typeFormatter = Object.fromEntries(
        this.typeOptions.map(({ k, v }) => [k, v])
      );

      this.tableLoading = false;
    },

    /**
     * 新增文库
     * @param {*}
     */
    addAccountClick() {
      this.addEditForm={}
      this.title = "新增文库";
      this.addEditDialogVisible = true;
    },
    /**
     * 编辑按钮
     * @param {*} row
     */
    async editClick(row, index) {
      this.title = "编辑文库";
      this.addEditDialogVisible = true;
      this.editId = row.id;

      this.$nextTick(() => {
        this.addEditForm = JSON.parse(JSON.stringify(this.tableData[index]));
      });
    },
    /**
     * 删除按钮
     * @param {*} row
     */
    delClick(row) {
      this.$confirm(
        "删除后，PC和小程序端将不再显示。此操作不可恢复，确认继续删除吗?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$api.delStandard(row.id).then((res) => {
            if (res.data.code == "00000") {
              this.$message.success("删除成功");
              this.getStandardList();
            }
          });
        })
        .catch(() => {});
    },

    /**
     * 切换页面大小
     * @param {*} val
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getStandardList();
    },

    /**
     * 页码切换
     * @param {*} val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.getStandardList();
    },

    /**
     * 打开新增和修改的回调
     * @param {*}
     */
    addEditDialogOpen() {
        this.progressPercentExcel=0
      this.showJinDuTaoExcel=false
      if (this.$refs.addEditFormRef) this.$refs.addEditFormRef.resetFields();
    },

    /**
     * 新增编辑保存按钮
     * @param {*}
     */
    addEditDialogSaveClick() {
      this.$refs.addEditFormRef.validate(async (boolean) => {
        if (boolean) {
          let data = {
            id: this.editId,
            ...this.addEditForm,
          };
          if (this.title == "新增文库") {
            data.id = "";
            const res = await this.$api.addStandard(data);
            if (res.data.code == "00000") {
              this.$message.success("新增成功");
              this.getStandardList();
              this.addEditDialogVisible = false;
            }
          } else {
            const res = await this.$api.editStandard(data);
            if (res.data.code == "00000") {
              this.$message.success("修改成功");
              this.getStandardList();
              this.addEditDialogVisible = false;
            }
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.accountList {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  .searchBox {
    .el-row {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        margin-bottom: 0;
      }
      .item {
        display: flex;
        align-items: center;
        margin-right: 20px;
        .nameSpan {
          padding-right: 10px;
          box-sizing: border-box;
          white-space: nowrap;
        }
        .el-input {
          width: 162px;
        }
      }
    }
  }
   .topBtn {
    margin: 10px 0;
text-align: right;
  }
  .addEditAccountDialog {
    .el-form-item {
      .el-select {
        width: 100%;
      }
    }
    .btns {
      text-align: right;
      margin-bottom: 0;
    }
  }
}
/deep/.el-button--success.is-plain {
  color: #fff;
  border-color: #409eff;
  background-color: #409eff;
}
/deep/.el-form-item {
  margin-bottom: 12px;
}
</style>